package com.zhiyuancode.parse;

import com.zhiyuancode.conf.Bean;
import com.zhiyuancode.conf.Property;
import com.zhiyuancode.conf.Scope;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨志远[OF2551]
 * email faryangsh@163.com
 * Date    2018-11-23
 */
public class ConfigManager {

    public static Map<String, Bean> getConfig(String path) {
        Map<String, Bean> beanMap = new HashMap<String, Bean>();


        SAXReader reader = new SAXReader();
        InputStream stream = ConfigManager.class.getResourceAsStream(path);
        Document doc = null;
        try {
            doc = reader.read(stream);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("xml configure is not right");
        }
        String xpath = "//bean";
        List<Element> list = doc.selectNodes(xpath);

        if (list != null) {
            for (Element beanEle : list) {
                String name = beanEle.attributeValue("name");
                String className = beanEle.attributeValue("class");
                Scope scope = Scope.genetateScope(beanEle.attributeValue("scope"));

                Bean bean = Bean.builder()
                        .className(className)
                        .name(name)
                        .properties(new ArrayList<>())
                        .scope(scope) // 默认单例
                        .build();
                List<Element> children = beanEle.elements("property");

                if (children != null) {
                    for (Element child : children) {
                        String nameProp = child.attributeValue("name");
                        String valueProp = child.attributeValue("value");
                        String refProp = child.attributeValue("ref");

                        Property property = Property.builder()
                                .name(nameProp)
                                .value(valueProp)
                                .ref(refProp)
                                .build();
                        bean.getProperties().add(property);

                    }

                }
                beanMap.put(name, bean);
            }

        }

        return beanMap;
    }

    public static void main(String[] args) {
        Scope scope = Scope.genetateScope("");
        System.out.println(scope);

    }
}
